package com.android.logcat;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author GYL
 * @version 1.0
 * @dateTime 2020/7/1-11:45
 * @description
 */
/*public*/ class LoggerRunnable implements Runnable {
  private ConcurrentLinkedQueue<LoggerContent> msgQueue = new ConcurrentLinkedQueue<LoggerContent>();
  private boolean isStart = false;
  private LoggerConfig mLoggerConfig;
  
  LoggerRunnable(LoggerConfig loggerConfig){
    this.mLoggerConfig=loggerConfig;
  }
  
  @Override
  public void run() {
    while (isStart) {
      if (!msgQueue.isEmpty()) {
        LoggerContent loggerContent=msgQueue.poll();
        StringBuffer content = new StringBuffer("");
        content.append(loggerContent.getTime()).append(" ")
          .append(loggerContent.getLogLevel()).append("/")
          .append(loggerContent.getTagName()).append(":: ")
          .append(loggerContent.getContent()).append("\r\n");
        //
        Throwable throwable=loggerContent.getThrowable();
        if(throwable!=null){
          Writer writer=null;
          PrintWriter printWriter=null;
          try {
            writer = new StringWriter();
            printWriter = new PrintWriter(writer);
            throwable.printStackTrace(printWriter);
            content.append(writer);
          }catch (Exception e){
            e.printStackTrace();
          }finally {
            if(writer!=null){
              try { writer.close(); }catch (Exception e){}
            }
            if(printWriter!=null){
              try { printWriter.close(); }catch (Exception e){}
            }
          }
        }
        mLoggerConfig.getLogFileWriteMonitor().logger(loggerContent.getLogLevel(),content.toString());
        //如果不为空，则调用log显示接口
        if(mLoggerConfig.getLogViewMonitor()!=null){
          mLoggerConfig.getLogViewMonitor().logger(loggerContent.getLogLevel(),content.toString());
        }
      }
    }
  }
  
  public void off() {
    if (isStart) {
      this.isStart = false;
      mLoggerConfig.shutdown(this);
    }
  }
  
  public void on() {
    if (!isStart) {
      isStart = true;
      mLoggerConfig.execRunnable(this);
    }
  }
  
  public synchronized void addLogger(LoggerContent loggerContent) {
    msgQueue.add(loggerContent);
  }
}
